package com.example.blogsystem.demos.controller;

import com.example.blogsystem.demos.model.Result;
import com.example.blogsystem.demos.model.UserInfo;
import com.example.blogsystem.demos.service.UserService;
import com.example.blogsystem.demos.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName, String password){
        log.info(userName);
        log.info(password);

        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }

        UserInfo userInfo = userService.queryByName(userName);
        if (userInfo == null || userInfo.getId() < 0){
            return Result.fail("用户不存在");
        }

        if (!password.equals(userInfo.getPassword())){
            return Result.fail("密码错误");
        }

        //生成Token并返回
        Map<String, Object> claim = new HashMap<>();
        claim.put("id", userInfo.getId());
        claim.put("name", userInfo.getUserName());
        String token = JwtUtils.genToken(claim);
        return Result.success(token);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId == null){
            return null;
        }

        return userService.queryById(userId);
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        log.info("blogId:" + blogId);
        return userService.getAuthorInfo(blogId);
    }
}
